package cn.com.darly.videoandroidpm.ui.conversation.chat;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.darly.common.ToastApp;
import com.darly.dview.framework.ContentBinder;
import com.darly.dview.framework.ViewsBinder;
import com.darly.dview.widget.header.TitleView;

import java.util.List;

import cn.com.darly.videoandroidpm.R;
import cn.com.darly.videoandroidpm.base.BaseActivity;
import cn.com.darly.videoandroidpm.bean.LoginInfo;
import cn.com.darly.videoandroidpm.common.SharePreferHelp;
import cn.com.darly.videoandroidpm.common.StaticListener;
import cn.com.darly.videoandroidpm.common.StaticListener.OnMessageChangeListener;
import cn.com.darly.videoandroidpm.common.dao.ConversationMessageInfo;
import cn.com.darly.videoandroidpm.ui.adapter.ConversationRecyclerAdapter;
import cn.com.darly.videoandroidpm.ui.biz.ConversationListener.ConversationInterface;
import cn.com.darly.videoandroidpm.ui.conversation.SoftKeyboardStateWatcher;
import cn.com.darly.videoandroidpm.ui.presenter.ConversationPresenter;

/** 用户之间的会话窗口，点击进来后首先获取自己和好友信息，并且从本地数据库中获取以前的会话记录。
 * @author Darly/张宇辉/2018/5/18 15:22
 * @version 1.0/cn.com.darly.videoandroidpm.ui.conversation
 */
@ContentBinder(R.layout.activity_conversation)
public class ConversationActivity extends BaseActivity implements OnClickListener,ConversationInterface,OnMessageChangeListener {

    @ViewsBinder(R.id.id_base_title)
    TitleView id_base_title;

    private LoginInfo friend;

    private LoginInfo user;

    @ViewsBinder(R.id.id_conversation_list)
    RecyclerView id_conversation_list;
    @ViewsBinder(R.id.id_conversation_et)
    EditText id_conversation_et;
    @ViewsBinder(R.id.id_conversation_btn)
    Button id_conversation_btn;

    private ConversationRecyclerAdapter adapter;

    private ConversationPresenter presenter ;

    @Override
    protected void initView(Bundle savedInstanceState) {
        friend = (LoginInfo) getIntent().getSerializableExtra("LoginInfo");
        if (friend==null) {
            String from = getIntent().getStringExtra("from");
            String name = getIntent().getStringExtra("name");
            String icon = getIntent().getStringExtra("icon");
            if (TextUtils.isEmpty(from)||TextUtils.isEmpty(name)){
                ToastApp.showToast("好友信息错误");
                finish();
            }
            friend = new LoginInfo();
            friend.setId(from);
            friend.setName(name);
            friend.setIcon(icon);
        }
        id_base_title.setTitle(friend.getName());
        id_base_title.removeBackground(R.drawable.ic_title_background);
        user = (LoginInfo) SharePreferHelp.getValue("LoginInfo");
        if (user == null){
            ToastApp.showToast("用户信息错误");
            finish();
        }

        presenter = new ConversationPresenter(this);

    }

    @Override
    protected void loadData() {
        //在這裡進行用戶歷史信息展示
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        id_conversation_list.setLayoutManager(linearLayoutManager);
        adapter = new ConversationRecyclerAdapter(this, null,friend,user);
        id_conversation_list.setAdapter(adapter);
        //初试加载历史记录呈现最新消息
        id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);

        presenter.getMessageFromDB(user.getId(),friend.getId());
    }

    @Override
    protected void initListener() {
        StaticListener.setOnMessageChangeListener(this);
        id_base_title.setLeftBackOneListener(R.mipmap.ic_title_back,this);
        id_conversation_btn.setOnClickListener(this);
        //设置下滑隐藏软键盘
        id_conversation_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < -10) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(id_conversation_et.getWindowToken(), 0);
                }
            }
        });

        SoftKeyboardStateWatcher watcher = new SoftKeyboardStateWatcher(id_conversation_list);
        watcher.addSoftKeyboardStateListener(new SoftKeyboardStateWatcher.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);
            }

            @Override
            public void onSoftKeyboardClosed() {

            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_view_back_img:
                finish();
                break;
            case R.id.id_conversation_btn:
                String content = id_conversation_et.getText().toString();
                //在数据库中插入一条数据，并上传到服务端
                if (TextUtils.isEmpty(content)){
                    //假如消息为空，则不能发送。
                    ToastApp.showToast("发送消息不能为空，请重新输入消息。");
                    return;
                }
                presenter.saveConversationMessage(user.getId(),content,friend.getId());
                id_conversation_et.setText("");
                break;
        }
    }

    @Override
    public void setDisableClick() {

    }

    @Override
    public void setEnableClick() {

    }

    @Override
    public void onConversationSuccess(List<ConversationMessageInfo> code) {
        adapter.setData(code);
        id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public void onConversationFailed(String info) {

    }

    @Override
    public void end() {

    }
    //新增消息
    @Override
    public void addNewMessage(ConversationMessageInfo info) {
        adapter.addItem(info);
        id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public void sendMessageOK(ConversationMessageInfo sendMsg) {
        adapter.msgSendOK(sendMsg);
        id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);
    }

    @Override
    public boolean messageChange(ConversationMessageInfo info ) {
        if (friend.getId().equals(info.getMsgFrom())){
            //刷新页面
            adapter.addItem(info);
            id_conversation_list.scrollToPosition(adapter.getItemCount() - 1);
            return true;
        }else {
            //用户打开其他会话，不进行刷新
            return false;
        }
    }
}
